android 反射使用——反射获取IWIndowManager中方法的使用

话不多说直接上代码,代码含义注释里有

Method getRotation ;
Object IWindowManager ;
public void getRotation(){
        try {
            //加载得到ServiceManager类,然后得到方法getService。
            Method getServiceMethod = Class.forName("android.os.ServiceManager").getDeclaredMethod("getService", new Class[]{String.class});
            //通过getServiceMethod得到ServiceManager的实例(隐藏类,所以使用Object)
            Object ServiceManager = getServiceMethod.invoke(null, new Object[]{"window"});
            //通过反射的到Stub
            Class<?> cStub =  Class.forName("android.view.IWindowManager$Stub");
            //得到Stub类的asInterface 方法
            Method asInterface = cStub.getMethod("asInterface", IBinder.class);
            //然后通过类似serviceManager.getIWindowManager的方法获取IWindowManager的实例
            IWindowManager = asInterface.invoke(null, ServiceManager);
            //通过IWindowManager的实例得到方法getRotation
            getRotation = IWindowManager.getClass().getMethod("getRotation");

        } catch (Exception e) {
            Log.e("wmb", "--shutDown has an exception");
            e.printStackTrace();
        }
    }

使用Method方法时,只需

int x = (int)getRotation.invoke(IWindowManager);

这里要注意的最后一句IWindowManager.getClass().getMethod(“getRotation”);中的getMethod方法,中的参数可以是多个的,看了一下源码

  private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)
            throws NoSuchMethodException {
        if (name == null) {
            throw new NullPointerException("name == null");
        }
        if (parameterTypes == null) {
            parameterTypes = EmptyArray.CLASS;
        }
        for (Class<?> c : parameterTypes) {
            if (c == null) {
                throw new NoSuchMethodException("parameter type is null");
            }
        }
        Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes)
                                               : getDeclaredMethodInternal(name, parameterTypes);
        // Fail if we didn't find the method or it was expected to be public.
        if (result == null ||
            (recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) {
            throw new NoSuchMethodException(name + " " + Arrays.toString(parameterTypes));
        }
        return result;
    }

这里第二个参数parameterTypes,就是这个方法需要传入的参数类型。第三个参数默认就是true。
比如如果getRotation方法需要传入参数,那么获取这个方法时应该

getRotation = IWindowManager.getClass().getMethod("getRotation",boolean.class,String.class);

调用方法时就是

int x = (int)getRotation.invoke(IWindowManager,false,"param");
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值